package com.yonyou.distribute.zk;


import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.CountDownLatch;


public class ZKTest {

    private ZooKeeper zooKeeper;


    public void init(){
        try {
            // 计数器对象
            CountDownLatch countDownLatch=new CountDownLatch(1);
            // arg1:服务器的ip和端口
            // arg2:客户端与服务器之间的会话超时时间  以毫秒为单位的
            // arg3:监视器对象
            zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    if(event.getState() == Event.KeeperState.SyncConnected) {
                        System.out.println("连接创建成功！");
                        countDownLatch.countDown();
                    }else if(event.getState() == Event.KeeperState.Closed){
                        System.out.println("关闭连接！");
                    }
                }
            });
            // 主线程阻塞等待连接对象的创建成功
            countDownLatch.await();

            //1、 节点新增：永久、临时、永久序列化、临时序列化
            zooKeeper.create("/test1", "hello zk".getBytes(StandardCharsets.UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            zooKeeper.create("/test2", "hello zk".getBytes(StandardCharsets.UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
            zooKeeper.create("/test3", "hello zk".getBytes(StandardCharsets.UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
            zooKeeper.create("/test4", "hello zk".getBytes(StandardCharsets.UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);

            //2、查询 判断节点是否存在
            Stat stat = zooKeeper.exists("/test1", false);
            //2、查询 获取当前节点内容
            byte[] data = zooKeeper.getData("/test1", false, stat);
            System.out.println(new String(data));
            //2、查询 获取当前节点的子节点
            List<String> children = zooKeeper.getChildren("/test", false);

            //3、更新
            Stat stat1 = zooKeeper.setData("/test1", "haha".getBytes(StandardCharsets.UTF_8), stat.getVersion());//版本号 设置-1  不关心版本号
            //4、删除
            zooKeeper.delete("/test1", -1);

            System.in.read();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
